package top.archiesean.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * 1. 发送消息
 * 2. 接收消息
 *
 * @author ArchieSean
 * @description 客户端处理类
 * @date 2024-03-06
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext ctx;

    private String requestMsg;

    private String responseMsg;

    public void setRequestMsg(String requestMsg) {
        this.requestMsg = requestMsg;
    }

    /**
     * 通道就绪事件
     *
     * @param ctx 上下文
     * @throws Exception ex
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;
    }

    @Override
    protected synchronized  void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        this.responseMsg = s;
        //唤醒等待线程
        notify();
    }

    /**
     * 发送消息到服务端
     *
     * @return
     * @throws Exception
     */
    @Override
    public synchronized  Object call() throws Exception {
        //消息发送
        ctx.writeAndFlush(requestMsg);
        //线程等待
        wait();
        return responseMsg;
    }
}
